package com.zbkj.business.core.pay.wxpay;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ijpay.core.IJPayHttpResponse;
import com.ijpay.core.enums.RequestMethodEnum;
import com.ijpay.core.kit.PayKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.core.utils.DateTimeZoneUtil;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.enums.WxDomainEnum;
import com.ijpay.wxpay.enums.v3.BasePayApiEnum;
import com.ijpay.wxpay.model.v3.Amount;
import com.ijpay.wxpay.model.v3.Payer;
import com.ijpay.wxpay.model.v3.UnifiedOrderModel;
import com.zbkj.common.response.CommonResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.security.cert.X509Certificate;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class WxpayUtils {
    private final WxpayConfig wxpayConfig;

    public Map<String, String> appPay(String goodsName, String tradeNo, Integer amount) {
        try {
            String timeExpire = DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + 1000 * 60 * 3);
            UnifiedOrderModel unifiedOrderModel = new UnifiedOrderModel()
                    // APPID
                    .setAppid(wxpayConfig.getAppid())
                    // 商户号
                    .setMchid(wxpayConfig.getMchid())
                    .setDescription(goodsName)
                    .setOut_trade_no(tradeNo)
                    .setTime_expire(timeExpire)
                    .setAttach("微信系开发脚手架 https://gitee.com/javen205/TNWX")
                    .setNotify_url(wxpayConfig.getNotifyUrl())
                    .setAmount(new Amount().setTotal(amount)
                            //.setPayer(new Payer().setOpenid(openId)
                    );

            log.info("统一下单参数 {}", JSONUtil.toJsonStr(unifiedOrderModel));
            IJPayHttpResponse response = WxPayApi.v3(
                    RequestMethodEnum.POST,
                    WxDomainEnum.CHINA.toString(),
                    BasePayApiEnum.JS_API_PAY.toString(),
                    wxpayConfig.getMchid(),
                    getSerialNumber(),
                    null,
                    wxpayConfig.getCertKeyPath(),
                    JSONUtil.toJsonStr(unifiedOrderModel)
            );
            log.info("统一下单响应 {}", response);
            // 根据证书序列号查询对应的证书来验证签名结果
            boolean verifySignature = WxPayKit.verifySignature(response, wxpayConfig.getPlatFormPath());
            log.info("verifySignature: {}", verifySignature);
            if (response.getStatus() == HttpStatus.HTTP_OK && verifySignature) {
                String body = response.getBody();
                JSONObject jsonObject = JSONUtil.parseObj(body);
                String prepayId = jsonObject.getStr("prepay_id");

                Map<String, String> map = WxPayKit.appCreateSign(wxpayConfig.getAppid(), "", prepayId, wxpayConfig.getCertKeyPath());
//                Map<String, String> map = WxPayKit.jsApiCreateSign(wxpayConfig.getAppid(), prepayId, wxpayConfig.getCertKeyPath());
                log.info("唤起支付参数:{}", map);
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getSerialNumber() {
        // 获取证书序列号
        X509Certificate certificate = PayKit.getCertificate(wxpayConfig.getCertPath());
        if (null != certificate) {
            String serialNo = certificate.getSerialNumber().toString(16).toUpperCase();
            // 提前两天检查证书是否有效
            boolean isValid = PayKit.checkCertificateIsValid(certificate, wxpayConfig.getMchid(), -2);
            log.info("证书是否可用 {} 证书有效期为 {}", isValid, DateUtil.format(certificate.getNotAfter(), DatePattern.NORM_DATETIME_PATTERN));
            System.out.println("serialNo:" + serialNo);
            return serialNo;
        }
        return null;
    }
}
